package com.isoft.c2team3service2.controller;

import com.isoft.c2team3service2.common.Result;
import com.isoft.c2team3service2.dto.CommentDTO;
import com.isoft.c2team3service2.entity.Comment;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.service.CommentService;
import com.isoft.c2team3service2.util.UserHolder;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {
    private static final Logger log = LoggerFactory.getLogger(CommentController.class);
    @Resource
    private CommentService commentService;

    // 关键修改：接口路径和方法名同步为“按帖子ID查评论”
    @GetMapping("/post/{postId}") // 路径从/article/{articleId} → /post/{postId}
    public Result<List<CommentDTO>> getCommentsByPostId(@PathVariable Integer postId) {
        List<CommentDTO> comments = commentService.getCommentsByPostId(postId);
        return Result.success(comments);
    }

    // 新增评论时，前端需传入postId（而非articleId），此处无需修改方法，仅需前端传参对应
    @PostMapping
    public Result<?> addComment(@RequestBody Comment comment) {
        Integer commentId = commentService.addComment(comment);
        if (commentId  == 0){
            return Result.error("帖子存在敏感词，请重新输入！评论帖子");
        } else if (commentId != null ) {
            UserDTO user = UserHolder.getUser();
            log.info("当前用户ID：{}，昵称：{}，新增评论ID：{}", user.getId(), user.getNickName(), commentId);
            return Result.successWithCommentId(null, commentId, user.getNickName());
        }
            return Result.error("添加评论失败");
    }

    // （updateComment、deleteComment方法无需修改，已同步关联postId）
    @PutMapping("/{commentId}")
    public Result<?> updateComment(@PathVariable Integer commentId, @RequestBody Comment updatedComment) {
        log.info("接收到的更新内容：{}", updatedComment.getContent());
        boolean success = commentService.updateComment(commentId, updatedComment);
        if (success) {
            UserDTO user = UserHolder.getUser();
            return Result.successWithCommentId(null, commentId, user.getNickName());
        }
        return Result.error("更新失败或涉及敏感字眼");
    }

    @DeleteMapping("/del/{commentId}")
    public Result<?> deleteComment(@PathVariable Integer commentId) {
        UserDTO user = UserHolder.getUser();
        boolean success = commentService.deleteComment(commentId, user.getId());
        return success ? Result.success() : Result.error("删除失败或无权限");
    }
}